package com.health.work.activity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.health.work.R;
import com.health.work.other.TopViewEvent;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.Tools;
import com.health.work.utils.UserInfoUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * 项目名称：HealthNet 类名称：MainActivity 类描述：主页面 创建人：Zhai 创建时间：2012-11-8 下午1:38:14
 * 修改人：Zhai 修改时间：2012-11-8 下午1:38:14 修改备注：
 * 
 * @version
 * 
 */
public class MainActivity extends Activity implements OnClickListener {

	protected static final int LOGIN = 1;
	protected static final int REGIST = 2;
	protected static final int ERROR = 0;
	protected static final int CHANGEPWDERROR = 3;
	protected static final int NETERROR=9999;
	private Gallery mGallery;
	private TextView mShare;
	private TextView mSuggest;
	private Button mLogin;
	private Button mRegister;
	private Button mChangePwd;
	private EditText mPhone;
	private EditText mPwd;
	private ImageView point;
	private Bitmap normal;
	private Bitmap select;
	private SharedPreferences pre;
	private String MembershipType;
	private ProgressDialog dialog;
	private Handler handler = new Handler() {
		private Intent i;

		public void handleMessage(Message msg) {
			dia();
			switch (msg.what) {
			case LOGIN:

				if(MembershipType!=null &&"公众会员".equals(MembershipType)){
					i = new Intent(MainActivity.this,HealthPassportActivity.class);
					startActivity(i);
					finish();
				}else if(MembershipType!=null &&"医护人员".equals(MembershipType)){
					i = new Intent(MainActivity.this,DoctorUserActivity.class);
					startActivity(i);
					finish();
				}else if(MembershipType!=null &&"产品商家".equals(MembershipType)){
					i = new Intent(MainActivity.this,SellerUserActivity.class);
					startActivity(i);
					finish();
				}else if(MembershipType!=null &&"医护专家".equals(MembershipType)){
					i = new Intent(MainActivity.this,ExpertUserActivity.class);
					startActivity(i);
					finish();
				}else if(MembershipType!=null &&"档案会员".equals(MembershipType)){
					i = new Intent(MainActivity.this,HealthPassportActivity.class);
					startActivity(i);
					finish();
				}
				break;
			case REGIST:
				
				break;
			case ERROR:
				TipsUtil.showAlert(MainActivity.this, null,
						"登录失败，用户名或密码不正确。");
				break;
			case NETERROR:
				TipsUtil.showAlert(MainActivity.this, null,
						"网络请求异常，请检查网络");
				break;
			case CHANGEPWDERROR:
				TipsUtil.showAlert(MainActivity.this, null,
						"因用户名或密码不正确，无法进入修改密码");
				break;
			default:
				break;
			}

		}

	};
	private Thread thread;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void dia(){
		if (dialog != null) {
			dialog.cancel();
			dialog=null;
		} else {
			dialog = ProgressDialog.show(this, "", "正在加载数据，请稍候...");
			dialog.setCancelable(true);
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
//		 Intent intent = new Intent(); 
//         intent.setClass(this,RegisteProductInfoInputActivity.class); 
//         startActivity(intent); 
	}

	/**
	 * 
	 * init(初始化ui)
	 * 
	 * @param name
	 * @param null
	 * @return Void
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	private void init() {
		mShare = (TextView) this.findViewById(R.id.btnShare);
		mSuggest = (TextView) this.findViewById(R.id.btnSuggest);
		mLogin = (Button) this.findViewById(R.id.btnLogin);
		mRegister = (Button) this.findViewById(R.id.btnRegister);
		mChangePwd = (Button) this.findViewById(R.id.btnModifyPwd);
		mPhone = (EditText) this.findViewById(R.id.phone);
		mPwd = (EditText) this.findViewById(R.id.password);
		point = (ImageView) this.findViewById(R.id.point);
		
		//此处根据输入手机好是否完成 来判断密码是否可输入
		mPhone.setFocusableInTouchMode(true);
		String tel=UserInfoUtils.getUserProperty(this, HEALTHPASSPORT.MOBILEPHONE);
		if(!"".equals(tel)){
			mPhone.setText(UserInfoUtils.getUserProperty(this, HEALTHPASSPORT.MOBILEPHONE));
		}
		mPwd.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(mPhone.getText()!=null && mPhone.getText().toString().length()>=4){
					mPwd.setFocusableInTouchMode(true);
				}else{
					mPwd.setFocusableInTouchMode(false);
				}
				return false;
			}
		});

		mShare.setOnClickListener(this);
		mSuggest.setOnClickListener(this);
		mLogin.setOnClickListener(this);
		mChangePwd.setOnClickListener(this);
		mRegister.setOnClickListener(this);

		normal = ((BitmapDrawable) getResources().getDrawable(
				R.drawable.product_point_normal)).getBitmap();
		select = ((BitmapDrawable) getResources().getDrawable(
				R.drawable.product_point_selected)).getBitmap();
		mGallery = (Gallery) this.findViewById(R.id.galleryPic);
		ImageAdapter adapter = new ImageAdapter(this);
		mGallery.setAdapter(adapter);
		point.setImageBitmap(drawPoint(6, 0));
		mGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View v,
					int position, long id) {
				point.setImageBitmap(drawPoint(6, position));
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		mGallery.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				TipsUtil.showForwordTips(MainActivity.this, null, "访问我们网站浏览更多信息");
				return false;
			}
		});
	}

	/*
	 * 绘制图片点
	 */
	public Bitmap drawPoint(int num, int position) {
		if (num <= 0) {// 加上判断，有时再颜色频繁切换时，会出现异常
			num = 1;
		}

		Bitmap bitmap = Bitmap.createBitmap(num * 15, 15,
				Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		int x = 0;
		for (int i = 0; i < num; i++) {
			if (i == position) {
				canvas.drawBitmap(select, x, 0, null);
			} else {
				canvas.drawBitmap(normal, x, 0, null);
			}
			x += 15;
		}
		return bitmap;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK){
			TipsUtil.showExit(this);
			return true;
		}else{
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnSuggest:
			TopViewEvent.viewSuggest(this);
			break;
		case R.id.btnShare:
			TopViewEvent.viewShare(this);
			break;
		case R.id.btnLogin:
			if (mPhone.getText() != null
//					&& mPhone.getText().toString().length() == 11
					&& mPhone.getText().toString().length() > 0
					&& mPwd.getText() != null
					&& mPwd.getText().toString().length() >= 4 
					&& UserInfoUtils.passwordInvildet(mPwd.getText().toString())) {
					login();
			} else {
				numAndPasswordInput();
			}

			break;
		case R.id.btnRegister:
			// showTips();
			if (mPhone.getText() == null
			|| mPhone.getText().toString().length() == 0
		    || mPwd.getText() == null
			|| mPwd.getText().toString().length() == 0 ) {
				Toast.makeText(this, "您还没有注册，请直接输入用户名、密码一键注册，并牢记您的密码", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (mPhone.getText() != null
//					&& mPhone.getText().toString().length() == 11
					&& mPhone.getText().toString().length() > 3
					&& mPwd.getText() != null
					&& mPwd.getText().toString().length() >= 4
					&& UserInfoUtils.passwordInvildet(mPwd.getText().toString())) {
				 dia();
				new RequestParamtersUtil().Registration(mPhone.getText()
						.toString(), mPwd.getText().toString(),new Tools().readTelephoneSerialNum(this),
						new DefaultJSONData() {

							@Override
							public void parse(JSONObject object) {
								dia();
								Log.e("Registration", object.toString());
								saveUserInfo(object);
								showTips();
							}

							@Override
							public void parse(JSONArray array) {
								Log.e("Registration", array.toString());

							}

							@Override
							public void parse(String result)
									throws JSONException {
								Log.e("Registration", result);
								if ("1".equals(result)) {
									dia();
									TipsUtil.showAlert(MainActivity.this, null,
											"手机号已注册。");
								} else if("2".equals(result)) {
									dia();
									// 注册失败
									TipsUtil.showAlert(MainActivity.this, null,
											"注册失败。");
								}else if("3".equals(result)) {
									dia();
									// 此手机已经注册过 不能 重复注册
									TipsUtil.showAlert(MainActivity.this, null,
											"此手机已经注册过,不能重复注册。");
								}else if("9999".equals(result)){
									handler.sendEmptyMessage(NETERROR);
								}
							}
						});
			} else {
				numAndPasswordInput();
			}

			break;
		case R.id.btnModifyPwd:
			if (mPhone.getText() != null
//					&& mPhone.getText().toString().length() == 11
					&& mPhone.getText().toString().length() > 0
					&& mPwd.getText() != null
					&& mPwd.getText().toString().length() >= 4) {
				dia();
				new Thread(new Runnable() {
					@Override
					public void run() {
						new RequestParamtersUtil().Login(
								mPhone.getText().toString(),
								mPwd.getText().toString(),
								null, new DefaultJSONData() {

									@Override
									public void parse(JSONObject object)
											throws JSONException {
										dia();
										Log.e("Login", object.toString());
										String phoneNum = mPhone.getText()
												.toString();
										Intent i = new Intent(
												MainActivity.this,
												ChangePasswordActivity.class);
										i.putExtra("phoneNum", phoneNum);
										startActivity(i);
									}

									@Override
									public void parse(JSONArray array)
											throws JSONException {
									}

									@Override
									public void parse(String result)
											throws JSONException {
										Log.e("Login", result);
										if(result.equals("9999")){
											handler.sendEmptyMessage(NETERROR);
										}else{
											handler.sendEmptyMessage(CHANGEPWDERROR);
										}
									}
								});
					}
				}).start();
			} else {
				numAndPasswordInput();
			}

			break;
		default:
			break;
		}
	}
	private void login(){
			dia();
			new Thread(new Runnable() {
				@Override
				public void run() {
					new RequestParamtersUtil().Login(mPhone.getText().toString(),
							mPwd.getText().toString(),null, new DefaultJSONData() {
	
								@Override
								public void parse(JSONObject object)
										throws JSONException {
									Log.e("Login", object.toString());
									MembershipType=object.getString(HEALTHPASSPORT.MEMBERSHIPTYPE);
									saveUserInfo(object);
									handler.sendEmptyMessage(LOGIN);
								}
	
								@Override
								public void parse(JSONArray array)
										throws JSONException {
								}
	
								@Override
								public void parse(String result)
										throws JSONException {
									Log.e("Login", result);
									if(result.equals("9999")){
										handler.sendEmptyMessage(NETERROR);
									}else{
										handler.sendEmptyMessage(ERROR);
									}
								}
							});
					
				}
			}).start();
	}

	private void showTips() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("恭喜您");
		builder.setMessage(
//				"您已注册成为健康护照公众会员，系统赠送您10健康分，您已经可以在本软件进行免费健康咨询、聘请私人专家、查询采购本地区健康类商品，下面还需要进一步填写详细信息注册成为相关角色会员吗？")
				"您已注册为健康护照正式会员，获得四大免费服务：\n"+
				    "（1）获得系统赠送的10健康分；\n"+
				    "（2）免费健康咨询；\n"+
				    "（3）聘请私人专家；\n"+
					"（4）查询预订本地区健康类商品。\n"+
					"如果您是下列人员，请进一步注册成为:\n"+
					"(1)查档会员：可以查询自己的健康档案，目前对部分地区开放；\n"+
					"(2)医护人员：医生护士注册 \n"+
					"(3)本地商家：健康产品商家注册")
									.setCancelable(false)
				.setPositiveButton("不再注册", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Intent i = new Intent(MainActivity.this,
								HealthPassportActivity.class);
						startActivity(i);
					}
				})
				.setNegativeButton("进一步注册", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						Intent i = new Intent(MainActivity.this,
								RegisteSelectActivity.class);
						startActivity(i);
						dialog.cancel();
					}
				});
		builder.show();
	}

	private void saveUserInfo(JSONObject object) {
		pre = getSharedPreferences(HEALTHPASSPORT.USERINFO, 0);
		try {
			pre.edit()
					.putString(HEALTHPASSPORT.MOBILEPHONE,
							object.getString(HEALTHPASSPORT.MOBILEPHONE))
					.putString(HEALTHPASSPORT.ID,
							object.getString(HEALTHPASSPORT.ID))
					.putString(HEALTHPASSPORT.NAME,
							object.getString(HEALTHPASSPORT.NAME))
					.putString(HEALTHPASSPORT.IDNUMBER,
							object.getString(HEALTHPASSPORT.IDNUMBER))
					.putString(HEALTHPASSPORT.INTERGRAL,
							object.getString(HEALTHPASSPORT.INTERGRAL))
					.putString(HEALTHPASSPORT.MEMBERSHIPTYPE,
							object.getString(HEALTHPASSPORT.MEMBERSHIPTYPE))
					.putBoolean(HEALTHPASSPORT.ISTHROUGH,
							object.getBoolean(HEALTHPASSPORT.ISTHROUGH))
					.commit();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public class ImageAdapter extends BaseAdapter {
		// 用来设置ImageView的风格
		int mGalleryItemBackground;
		private Context context;
		// 图片的资源ID
		private Integer[] mImageIds = { R.drawable.jk01, R.drawable.jk02,
				R.drawable.jk03, R.drawable.jk04, R.drawable.jk05,
				R.drawable.jk06,

		};

		// 构造函数
		public ImageAdapter(Context context) {
			this.context = context;
		}

		// 返回所有图片的个数
		@Override
		public int getCount() {
			return mImageIds.length;
		}

		// 返回图片在资源的位置
		@Override
		public Object getItem(int position) {
			return position;
		}

		// 返回图片在资源的位置
		@Override
		public long getItemId(int position) {
			return position;
		}

		// 此方法是最主要的，他设置好的ImageView对象返回给Gallery
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ImageView imageView = new ImageView(context);
			// 通过索引获得图片并设置给ImageView
			imageView.setImageResource(mImageIds[position]);
			// 设置ImageView的伸缩规格，用了自带的属性值
			imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			// 设置布局参数
			imageView.setLayoutParams(new Gallery.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			// 设置风格，此风格的配置是在xml中
			imageView.setBackgroundResource(mGalleryItemBackground);
			return imageView;
		}

		public int getmGalleryItemBackground() {
			return mGalleryItemBackground;
		}

		public void setmGalleryItemBackground(int mGalleryItemBackground) {
			this.mGalleryItemBackground = mGalleryItemBackground;
		}

	}

	/**
	 * 登录，注册，修改密码时的限制条件
	 */
	private void numAndPasswordInput() {
		
		if (mPhone.getText() == null
				|| mPhone.getText().toString().length() < 11) {
//			Toast.makeText(this, "帐号号输入有误", Toast.LENGTH_SHORT).show();
		} else if (mPwd.getText() == null
				|| mPwd.getText().toString().length() < 4) {
			Toast.makeText(this, "密码输入长度有误", Toast.LENGTH_SHORT).show();
		}else if (mPwd.getText()!= null
				&& UserInfoUtils.passwordInvildet(mPwd.getText().toString())) {
			Toast.makeText(this, "密码相邻两位不能有重复", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, "手机号或密码输入有误", Toast.LENGTH_SHORT).show();
		}

	}
}
